const express = require('express')
const router = express.Router()
const verifyToken = require('../../middilWare/verifyToken')
const jwt = require('jsonwebtoken')
const SECRET_KEY = 'your_secret_key' // 建议放到环境变量或 config 文件
const {
  createUser,
  getUser,
  updateUserPassword,
  updateUserInfo,
  deleteUser,
  getAllUsers,
  userLogout,
  findAccount,
} = require('../../services/accountService')
const axios = require('axios')

console.log('commonUsers 路由已加载')

// 创建 axios 实例
const instance = axios.create({
  baseURL: 'http://localhost:<后端实际端口>/api',
  timeout: 5000,
})

// 用户注册
router.post('/register', async (req, res) => {
  try {
    const user = await createUser(req.body)
    if (user) {
      res.status(200).json({ code: 200, message: 'user register success' })
    } else {
      res.status(400).json({ code: 400, message: 'user register error' })
    }
  } catch (err) {
    res.status(500).json({ code: 500, message: 'register error' })
  }
})

// 用户登录
router.post('/login', async (req, res) => {
  try {
    const { name, password } = req.body
    const result = await findAccount({ name, password })
    if (result.status === 1) {
      // 生成 token，包含用户信息
      const token = jwt.sign(
        {
          id: result.user && result.user._id ? result.user._id : '',
          name: name,
          role: 'commonUser',
        },
        SECRET_KEY,
        { expiresIn: '7d' }
      )
      res.status(200).json({
        code: 200,
        message: 'login success',
        user: { name, role: 'commonUser', juri: result.user.juri },
        token,
      })
    } else {
      res.status(400).json({ code: 400, message: result.msg })
    }
  } catch (err) {
    res.status(500).json({ code: 500, message: 'login error' })
  }
})

// 获取所有用户（需token）
router.get('/', verifyToken, async (req, res) => {
  try {
    const users = await getAllUsers()
    res.status(200).json({ code: 200, users })
  } catch (err) {
    res.status(500).json({ code: 500, message: 'get users error' })
  }
})

module.exports = router
